import { RefreshTask, RefreshStats } from './types';
import { v4 as uuidv4 } from 'uuid';

export class TaskManager {
  private tasks: Map<string, RefreshTask> = new Map();
  private static instance: TaskManager;

  static getInstance(): TaskManager {
    if (!TaskManager.instance) {
      TaskManager.instance = new TaskManager();
    }
    return TaskManager.instance;
  }

  createTask(directoryPath: string, forceUpdate: boolean): RefreshTask {
    const task: RefreshTask = {
      id: uuidv4(),
      status: 'pending',
      startTime: new Date(),
      directoryPath,
      forceUpdate,
      progress: {
        processedFiles: 0,
        totalFiles: 0,
      },
    };
    
    this.tasks.set(task.id, task);
    return task;
  }

  getTask(taskId: string): RefreshTask | undefined {
    return this.tasks.get(taskId);
  }

  getAllTasks(): RefreshTask[] {
    return Array.from(this.tasks.values());
  }

  updateTaskProgress(
    taskId: string, 
    progress: RefreshTask['progress']
  ): void {
    const task = this.tasks.get(taskId);
    if (task) {
      task.progress = progress;
      this.tasks.set(taskId, task);
    }
  }

  updateTaskStatus(taskId: string, status: RefreshTask['status']): void {
    const task = this.tasks.get(taskId);
    if (task) {
      task.status = status;
      if (status === 'running' && !task.endTime) {
        // 确保任务开始时间正确设置
      }
      this.tasks.set(taskId, task);
    }
  }

  completeTask(taskId: string, stats: RefreshStats): void {
    const task = this.tasks.get(taskId);
    if (task) {
      task.status = 'completed';
      task.endTime = new Date();
      task.stats = stats;
      this.tasks.set(taskId, task);
    }
  }

  failTask(taskId: string, error: string): void {
    const task = this.tasks.get(taskId);
    if (task) {
      task.status = 'failed';
      task.endTime = new Date();
      task.error = error;
      this.tasks.set(taskId, task);
    }
  }

  // 清理老旧任务 (超过24小时的已完成/失败任务)
  cleanupOldTasks(): void {
    const cutoffTime = new Date(Date.now() - 24 * 60 * 60 * 1000); // 24小时前
    
    for (const [taskId, task] of this.tasks.entries()) {
      if (
        (task.status === 'completed' || task.status === 'failed') &&
        task.endTime &&
        task.endTime < cutoffTime
      ) {
        this.tasks.delete(taskId);
      }
    }
  }
}
